(function () {
    'use strict';

    // 初始化 Layui 模块
    layui.config({
        base: '/static/layui/'  // 根据实际路径调整
    }).use(['element', 'layer', 'jquery', 'util'], function () {
        const element = layui.element;
        const layer = layui.layer;
        const $ = layui.$;
        const util = layui.util;

        // ------------------------- 通用工具函数 -------------------------
        // 获取 CSRF Token
        function getCsrfToken() {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.startsWith('csrftoken=')) {
                        cookieValue = decodeURIComponent(cookie.substring('csrftoken='.length));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        // ------------------------- 菜单渲染逻辑 -------------------------
        // 动态渲染菜单
        function renderMenu(menuData) {
            const $menu = $('#menulist');
            $menu.empty(); // 清空旧菜单
        
            // 生成菜单结构
            const menuHtml = menuData.map((item, index) => {
                // 处理子菜单项
                const childrenHtml = item.children.map(child => {
                    // 自动补全路径规则（可选）
                    if (!child.path && child.menu_id) {
                        child.path = `/home/cd_${child.menu_id.slice(-2)}`;
                    }
                    return `
                        <dd>
                            <a href="javascript:;" 
                               menu-title="${child.title}" 
                               menuid="${child.menuid}" 
                               lay-href="${child.path}">
                                ${child.title}
                            </a>
                        </dd>
                    `;
                }).join('');
        
                // 主菜单项结构
                return `
                    <li class="layui-nav-item ${index === 0 ? 'layui-nav-itemed' : ''}">
                        <a href="javascript:;" 
                           menu-title="${item.title}" 
                           menuid="${item.parent_id}">
                            <span class="layui-icon layui-icon-home"></span>
                            <cite>${item.title}</cite>
                            <i class="layui-icon layui-icon-down layui-nav-more"></i>
                        </a>
                        <dl class="layui-nav-child">${childrenHtml}</dl>
                    </li>
                `;
            }).join('');
        
            $menu.html(menuHtml);
        
            // 强制重新渲染 Layui 导航组件
            layui.use('element', function() {
                const element = layui.element;
                element.init('nav');      // 初始化
                element.render('nav');    // 重新渲染
                element.render('tab');    // 渲染关联的 Tab 组件
            });
        }
        
        // 加载菜单数据
        function loadMenu() {
            $.ajax({
                url: '/mgr/api/get_menu',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'X-CSRFToken': getCsrfToken()
                },
                success: res => {
                    if (res.code === 0) {
                        renderMenu(res.data);
                        bindMenuEvents();  // 绑定菜单点击事件
                    }
                },
                error: xhr => layer.msg('菜单加载失败', { icon: 2 })
            });
        }

        // ------------------------- Tab 和 Iframe 管理 -------------------------
        // 绑定菜单点击事件
        function bindMenuEvents() {
            element.on('nav(side-menu)', function (elem) {
                const title = elem.attr('menu-title');
                const url = elem.attr('lay-href');
                const layId = elem.attr('menuid');

                // 添加或切换 Tab
                const tabElem = $(`[lay-id="${layId}"]`);
                if (tabElem.length === 0 && url) {
                    element.tabAdd('content', {
                        title: title,
                        content: `<iframe class="lay-iframe" lay-frameId="${layId}" src="${url}"></iframe>`,
                        id: layId
                    }); 
                }

                // 加载状态处理
                const iframe = $(`[lay-frameId="${layId}"]`);
                if (iframe.length > 0) {
                    const index = layer.load(2, { shade: 0, time: 8000 });
                    iframe.one('load error', function () {
                        layer.close(index);
                        if (this.contentWindow.document.URL === 'about:blank') {
                            layer.msg('页面加载失败', { icon: 2 });
                        }
                    });
                }

                element.tabChange('content', layId);
            });
        }

        // ------------------------- Tab 操作逻辑 -------------------------
        // 初始化 Tab 相关事件
        function initTabHandlers() {
            // Tab 删除监听
            element.on('tabDelete(content)', function (data) {
                const menuId = $(this).find('[lay-id]').eq(data.index).attr('lay-id');
                $(`[menuid="${menuId}"]`).parent().removeClass('layui-this');
            });

            // Tab 切换监听
            element.on('tab(content)', function (data) {
                const menuId = $(this).find('[lay-id]').eq(data.index).attr('lay-id');
                $('[lay-href]').parent().removeClass('layui-this');
                $(`[menuid="${menuId}"]`).parent().addClass('layui-this');
            });

            // Tab 操作按钮
            const tabActions = {
                closeAll: () => $('.layui-tab-close').trigger('click'),
                closeThis: () => {
                    const layId = $('.layui-tab-title .layui-this').attr('lay-id');
                    element.tabDelete('content', layId);
                },
                closeOther: () => {
                    const currentId = $('.layui-tab-title .layui-this').attr('lay-id');
                    $('.layui-tab-title li[lay-id]').each(function () {
                        const layId = $(this).attr('lay-id');
                        if (layId !== currentId) element.tabDelete('content', layId);
                    });
                }
            };

            $('#closeAll').click(tabActions.closeAll);
            $('#closeThis').click(tabActions.closeThis);
            $('#closeOther').click(tabActions.closeOther);
        }

        // ------------------------- 注销功能 -------------------------
        function initLogout() {
            $(document).on('click', '#logout-link', function (e) {
                e.preventDefault();
                layer.confirm('确定要退出系统吗？', { icon: 3 }, function () {
                    $.ajax({
                        url: '/mgr/api/signout',
                        method: 'POST',
                        headers: { 'X-CSRFToken': getCsrfToken() },
                        success: () => {
                            localStorage.clear();
                            location.href = '/mgr/view/signin';
                        },
                        error: () => layer.msg('退出失败，请重试', { icon: 2 })
                    });
                });
            });
        }

        // ------------------------- 全屏功能 -------------------------
        function initFullscreen() {
            $('[data-toggle="fullscreen"]').click(() => {
                const doc = document.documentElement;
                const requestFS = doc.requestFullscreen || doc.webkitRequestFullscreen;
                requestFS.call(doc);
            });
        }

        // ------------------------- 主初始化逻辑 -------------------------
        $(document).ready(function () {
            // 加载必要资源
            layer.load(2, { shade: 0, time: 10000 });
            $(window).on('load', () => layer.closeAll());

            // 初始化核心功能
            loadMenu();
            initTabHandlers();
            initLogout();
            initFullscreen();

            // 绑定全局刷新按钮
            $('.refresh').click(function () {
                const iframe = $(`[lay-frameId="${this.dataset.tabId}"]`);
                iframe.attr('src', iframe.attr('src'));
                layer.load(2, { shade: 0, time: 5000 });
            });
        });

    });

})();